/**
 * Resize function without multiple trigger
 * 
 * Usage:
 * $(window).smartresize(function(){  
 *     // code here
 * });
 */
(function($,sr){
    // debouncing function from John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    var debounce = function (func, threshold, execAsap) {
      var timeout;

        return function debounced () {
            var obj = this, args = arguments;
            function delayed () {
                if (!execAsap)
                    func.apply(obj, args); 
                timeout = null; 
            }

            if (timeout)
                clearTimeout(timeout);
            else if (execAsap)
                func.apply(obj, args);

            timeout = setTimeout(delayed, threshold || 100); 
        };
    };

    // smartresize 
    jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');
/**
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var CURRENT_URL = window.location.href.split('#')[0].split('?')[0],
    $BODY = $('body'),
    $MENU_TOGGLE = $('#menu_toggle'),
    $SIDEBAR_MENU = $('#sidebar-menu'),
    $SIDEBAR_FOOTER = $('.sidebar-footer'),
    $LEFT_COL = $('.left_col'),
    $RIGHT_COL = $('.right_col'),
    $NAV_MENU = $('.nav_menu'),
    $FOOTER = $('footer');

// Sidebar
$(document).ready(function() {
    // TODO: This is some kind of easy fix, maybe we can improve this
    var setContentHeight = function () {
        // reset height
        $RIGHT_COL.css('min-height', $(window).height());

        var bodyHeight = $BODY.outerHeight(),
            footerHeight = $BODY.hasClass('footer_fixed') ? -10 : $FOOTER.height(),
            leftColHeight = $LEFT_COL.eq(1).height() + $SIDEBAR_FOOTER.height(),
            contentHeight = bodyHeight < leftColHeight ? leftColHeight : bodyHeight;

        // normalize content
        contentHeight -= $NAV_MENU.height() + footerHeight;

        $RIGHT_COL.css('min-height', bodyHeight);
    };

    $SIDEBAR_MENU.find('a').on('click', function(ev) {
        var $li = $(this).parent();
        var $chevron = $(this).find("span.menu_chevron");

        if ($li.is('.active')) {
            $li.removeClass('active active-sm');
            $chevron.removeClass("fa-chevron-down");
            $chevron.addClass("fa-chevron-left");
            $('ul:first', $li).slideUp(function() {
                setContentHeight();
            });
        } else {
            // prevent closing menu if we are on child menu
            if (!$li.parent().is('.child_menu')) {
                $SIDEBAR_MENU.find('li').removeClass('active active-sm');
                $chevron.removeClass("fa-chevron-left");
                $chevron.addClass("fa-chevron-down");
                $SIDEBAR_MENU.find('li ul').slideUp();
            }

            $li.addClass('active');
            $chevron.removeClass("fa-chevron-left");
            $chevron.addClass("fa-chevron-down");

            $('ul:first', $li).slideDown(function() {
                setContentHeight();
            });
        }
    });

    // toggle small or large menu
    $MENU_TOGGLE.on('click', function() {
        if ($BODY.hasClass('nav-md')) {
            $SIDEBAR_MENU.find('li.active ul').hide();
            $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
        } else {
            $SIDEBAR_MENU.find('li.active-sm ul').show();
            $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
        }

        $BODY.toggleClass('nav-md nav-sm');

        setContentHeight();
    });

    // check active menu
    $SIDEBAR_MENU.find('a[href="' + CURRENT_URL + '"]').parent('li').addClass('current-page');

    $SIDEBAR_MENU.find('a').filter(function () {
        return this.href == CURRENT_URL;
    }).parent('li').addClass('current-page').parents('ul').slideDown(function() {
        setContentHeight();
    }).parent().addClass('active');

    // recompute content when resizing
    $(window).smartresize(function(){
        setContentHeight();
    });

    setContentHeight();

    // fixed sidebar
    if ($.fn.mCustomScrollbar) {
        $('.menu_fixed').mCustomScrollbar({
            autoHideScrollbar: true,
            theme: 'minimal',
            mouseWheel:{ preventDefault: true }
        });
    }
});
// /Sidebar

// Panel toolbox
$(document).ready(function() {
    $('.collapse-link').on('click', function() {
        var $BOX_PANEL = $(this).closest('.x_panel'),
            $ICON = $(this).find('i'),
            $BOX_CONTENT = $BOX_PANEL.find('.x_content');
        
        // fix for some div with hardcoded fix class
        if ($BOX_PANEL.attr('style')) {
            $BOX_CONTENT.slideToggle(200, function(){
                $BOX_PANEL.removeAttr('style');
            });
        } else {
            $BOX_CONTENT.slideToggle(200); 
            $BOX_PANEL.css('height', 'auto');  
        }

        $ICON.toggleClass('fa-chevron-up fa-chevron-down');
    });

    $('.close-link').click(function () {
        var $BOX_PANEL = $(this).closest('.x_panel');

        $BOX_PANEL.remove();
    });
});
// /Panel toolbox

// Tooltip
$(document).ready(function() {
    $('[data-toggle="tooltip"]').tooltip({
        container: 'body'
    });
});
// /Tooltip

// Progressbar
if ($(".progress .progress-bar")[0]) {
    $('.progress .progress-bar').progressbar();
}
// /Progressbar

// Switchery
$(document).ready(function() {
    if ($(".js-switch")[0]) {
        var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
        elems.forEach(function (html) {
            var switchery = new Switchery(html, {
                color: '#26B99A'
            });
        });
    }
});
// /Switchery

// iCheck
$(document).ready(function() {
    if ($("input.flat")[0]) {
        $(document).ready(function () {
            $('input.flat').iCheck({
                checkboxClass: 'icheckbox_flat-green',
                radioClass: 'iradio_flat-green'
            });
        });
    }
});
// /iCheck

// Table
$('table input').on('ifChecked', function () {
    checkState = '';
    $(this).parent().parent().parent().addClass('selected');
    countChecked();
});
$('table input').on('ifUnchecked', function () {
    checkState = '';
    $(this).parent().parent().parent().removeClass('selected');
    countChecked();
});

var checkState = '';

$('.bulk_action input').on('ifChecked', function () {
    checkState = '';
    $(this).parent().parent().parent().addClass('selected');
    countChecked();
});
$('.bulk_action input').on('ifUnchecked', function () {
    checkState = '';
    $(this).parent().parent().parent().removeClass('selected');
    countChecked();
});
$('.bulk_action input#check-all').on('ifChecked', function () {
    checkState = 'all';
    countChecked();
});
$('.bulk_action input#check-all').on('ifUnchecked', function () {
    checkState = 'none';
    countChecked();
});

function countChecked() {
    if (checkState === 'all') {
        $(".bulk_action input[name='table_records']").iCheck('check');
    }
    if (checkState === 'none') {
        $(".bulk_action input[name='table_records']").iCheck('uncheck');
    }

    var checkCount = $(".bulk_action input[name='table_records']:checked").length;

    if (checkCount) {
        $('.column-title').hide();
        $('.bulk-actions').show();
        $('.action-cnt').html(checkCount + ' Records Selected');
    } else {
        $('.column-title').show();
        $('.bulk-actions').hide();
    }
}

// Accordion
$(document).ready(function() {
    $(".expand").on("click", function () {
        $(this).next().slideToggle(200);
        $expand = $(this).find(">:first-child");

        if ($expand.text() == "+") {
            $expand.text("-");
        } else {
            $expand.text("+");
        }
    });
});

// NProgress
if (typeof NProgress != 'undefined') {
    $(document).ready(function () {
        NProgress.start();
    });

    $(window).load(function () {
        NProgress.done();
    });
}

$(function () {
    layer.config({
        extend: 'dakq/style.css'
    });
});

//显示错误信息
function showErrorMessage($message, callback)
{
    layer.msg($message, {
        skin: "dakq-error",
        offset: "t"
    }, function () {
        if (typeof callback === "function"){
            callback();
        }
    });
}

//显示成功信息
function showSuccessMessage($message, callback)
{
    layer.msg($message, {
        skin: "dakq-success",
        offset: "t"
    }, function () {
        if (typeof callback === "function"){
            callback();
        }
    });
}

//ajax请求
function ajaxRequest(url, data, successCallback)
{
    $.ajax({
        url: url,
        type: "POST",
        dataType: "JSON",
        data: data,
        success: function (json)
        {
            //操作成功
            if (json.status == 0)
            {
                if (typeof successCallback == "function")
                {
                    successCallback(json.info, json.data);
                }
            }
            //需要登录
            else if (json.status == -1)
            {
                if (window.parent)
                {
                    window.parent.location.href = json.url;
                }
                else
                {
                    location.href = json.url;
                }
            }
            else
            {
                showErrorMessage(json.info);
            }
        },
        error: function () {
            showErrorMessage("<?php echo translate('js-admin:ajax_error'); ?>");
        }
    })
}

//弹出模态框
function modal(url, title, width, height)
{
    //确定弹出框的尺寸
    width = typeof(width) == "undefined" ? "100%" : width;
    height = typeof(height) == "undefined" ? "100%" : height;

    //打开弹出框
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.8,
        area: [width, height],
        content: url
    });
}

//ajax提交表单
function ajaxSubmit(formId, isModal)
{
    //开启加载进度
    var loader = layer.load();
    //待操作表单
    var form = $("#" + formId);

    $.ajax({
        url: form.attr("action"),
        type: "POST",
        dataType: "JSON",
        data: form.serialize(),
        success: function (json)
        {
            //关闭加载进度
            layer.close(loader);

            if (json.status == 0)
            {
                isModal = typeof(isModal) == "undefined" ? false : true;

                if (isModal)
                {
                    showSuccessMessage(json.info, function () {
                        window.parent.location.reload(true);
                    });
                }
                else
                {
                    showSuccessMessage(json.info, function () {
                        location.reload(true);
                    });
                }
            }
            //需要登录
            else if (json.status == -1)
            {
                if (isModal)
                {
                    window.parent.location.href = json.url;
                }
                else
                {
                    location.href = json.url;
                }
            }
            else
            {
                showErrorMessage(json.info);
            }
        },
        error: function (json)
        {
            //关闭加载进度
            layer.close(loader);
        }
    });
}

//ajaxExcel 导入
function ajaxExcelSubmit(formId, isModal)
{
    layer.confirm('确认导入？导入过程中请勿刷新或关闭本页面', {title:'确认导入'}, function (index) {

        //开启加载进度
        var loader = layer.load();
        //待操作表单
        var form = $("#" + formId);

        $.ajax({
            url: form.attr("action"),
            timeout:1000*3600,//超时设置-毫秒-暂时设置1H
            type: "POST",
            dataType: "JSON",
            data: form.serialize(),
            success: function (json)
            {
                //关闭加载进度
                layer.close(loader);

                if (json.status == 0)
                {
                    var show_content = "<div style='padding:20px;'>";

                    show_content += "<p style='line-height: 30px;border-bottom: 1px solid #ccc;'>共计："+json.data.all_num+"条 失败："+json.data.fail_num+"条 成功："+json.data.success_num+"条</p>"

                    for(var ii=0;ii<json.data.fail_arr.length;ii++){
                        show_content += "<p style='line-height: 30px;color:red;border-bottom: 1px dashed #ccc;'>"+json.data.fail_arr[ii]+"</p>";
                    }
                    for(var ii=0;ii<json.data.success_arr.length;ii++){
                        show_content += "<p style='line-height: 30px;color:green;border-bottom: 1px dashed #ccc;'>"+json.data.success_arr[ii]+"</p>";
                    }

                    show_content += "</div>";

                    layer.open({
                        type: 1,
                        title: '导入结果',
                        shadeClose: true,
                        shade: 0.8,
                        area: ['70%','70%'],
                        content: show_content
                    });
                    // isModal = typeof(isModal) == "undefined" ? false : true;
                    //
                    // if (isModal)
                    // {
                    //     showSuccessMessage(json.info, function () {
                    //         window.parent.location.reload(true);
                    //     });
                    // }
                    // else
                    // {
                    //     showSuccessMessage(json.info, function () {
                    //         location.reload(true);
                    //     });
                    // }
                }
                //需要登录
                else if (json.status == -1)
                {
                    if (isModal)
                    {
                        window.parent.location.href = json.url;
                    }
                    else
                    {
                        location.href = json.url;
                    }
                }
                else
                {
                    showErrorMessage(json.info);
                }
            },
            error: function (json)
            {
                //关闭加载进度
                layer.close(loader);
            }
        });

        layer.close(index);
    });


}

$(function () 
{
    //询问按钮
    $("[data-toggle='confirm']").on("click", function () {
        //标题
        var title = $(this).attr("data-title");
        //信息内容
        var content = $(this).attr("data-content");
        //操作
        var operation = $(this).attr("data-operation");
        //超链
        var url = $(this).attr("data-url");

        layer.confirm(content, {title:title}, function (index) {

            if (operation)
            {
                window[operation]();
            }

            if (url)
            {   //开启加载进度
                var loader = layer.load();
                $.ajax({
                    url: url,
                    type: "GET",
                    dataType: "JSON",
                    success: function (json)
                    {
                        //关闭加载进度
                        layer.close(loader);

                        if (json.status == 0)
                        {   showSuccessMessage(json.info, function () {
                                location.reload(true);
                            });

                        }
                        else
                        {
                            showErrorMessage(json.info);
                        }
                    },
                    error: function (result)
                    {
                        //关闭加载进度
                        layer.close(loader);
                        showErrorMessage("操作失败！");
                    }
                });
            }

            layer.close(index);
        });
    });

    //更改状态按钮
    $("[data-toggle='ajaxSwitch']").on("click", function ()
    {
        //操作对象
        var object = $(this);

        if (object.attr("disable"))
        {
            return;
        }

        object.attr("disable", true);
        //存储原来的html内容
        var oldHtml = object.html();
        object.html("<img src='/static/images/loading.gif' style='width: 20px;'>");

        //获取当前状态值
        var status = object.attr("data-switch-status");

        //待操作值
        var value = object.attr("data-switch-value-" + status);

        //数值列表
        var valueList = value.split("|");

        $.ajax({
            type: "GET",
            url: valueList[3],
            dataType: "JSON",
            success: function (json) {
                if (json.status == 0)
                {
                    object.removeAttr("disable");
                    object.html(valueList[1]);
                    object.attr("class", valueList[2]);
                    object.attr("data-switch-status", valueList[0]);

                    //判断是否需要刷新
                    if (object.attr("data-reload"))
                    {
                        location.reload(true);
                    }
                }
                else
                {
                    object.removeAttr("disable");
                    object.html(oldHtml);
                }
            },
            error: function () {
                object.removeAttr("disable");
            }
        });
    })
});

//选择图片
function selectImage(imageId)
{
    //先使用ajax获取页面内容
    $.ajax({
        url: "/Utils/uploader",
        type: "GET",
        dataType: "JSON",
        data: {
            element_id: imageId
        },
        success: function (json) {
            if (json.status == 0)
            {
                //打开弹出框
                layer.open({
                    type: 1,
                    title: "",
                    shadeClose: true,
                    shade: 0.8,
                    area: ["80%", "80%"],
                    content: json.html
                });
            }
        }
    });
}

function ejectImg(src, title, width, height){
    //确定弹出框的尺寸
    width = typeof(width) == "undefined" ? "auto" : width;
    height = typeof(height) == "undefined" ? "auto" : height;
    title = typeof(title) == "undefined" ? "图片" : title;
    //打开弹出框
    var eject_img_content = "<img src='"+src+"' style='display:block;margin:0 auto;max-height: 700px;' />"
    layer.open({
        type: 1,
        title: title,
        shadeClose: true,
        shade: 0.8,
        area: [width,height],
        content: eject_img_content
    });
}


